<?php

namespace App\Http\Controllers\Web;

use App\Events\ArticleViewEvent;
use App\Http\Controllers\Controller;
use App\Http\Resources\CategoryResource;
use App\Models\Article;
use App\Models\Category;
use Illuminate\Http\Request;

class ArticleController extends Controller
{
    public function index(Request $request)
    {
        $categoryId = $request->input('category_id');
        $query = Article::query();
        if ($categoryId) {
            $query->where('category_id', $categoryId);
        }
        $articles = $query->orderBy('id')->get();
        return view('web.article', [
            'articles' => $articles,
            'categories' => Category::query()->orderBy('id')->get(),
            'category_id' => $categoryId,
        ]);
    }

    public function show($id)
    {
        $query = Article::query()->with('category');
        if (!$id) {
            return view('web.article_detail', [
                'error' => '抱歉，您浏览的文章不存在',
            ]);
        }
        $article = $query->find($id);
        if (!$article) {
            return view('web.article_detail', [
                'error' => '抱歉，您浏览的文章不存在',
            ]);
        }
        $article->increment('view_num');
        event(new ArticleViewEvent($article));
        return view('web.article_detail', [
            'article' => $article
        ]);
    }
}
